var count = Count();
var VOTE_NUM = 5;

function Count() {
    var num = 0;
    return {
        add: function() {
            num += 1;
        },
        reduce: function() {
            num -=1;
        },
        get count() {
            return num;
        }
    }
}

// 点击确定隐藏弹出层
$('.weui_btn_dialog').on('click', function() {
    $('.weui_dialog_alert').hide();
});


// 复选框的点击事件
$('.weui_check_label').on('click', function(event) {
    var checkbox = this.querySelector('.weui_check'); 
    checkbox.checked = !checkbox.checked;    //手动触发checkbox的点击事件
    checkbox.checked === true ? count.add() : count.reduce(); //计数
    if (count.count < VOTE_NUM) {
        if (!$('#submit_btn').hasClass('weui_btn_disabled')) {
            $('#submit_btn').addClass('weui_btn_disabled');
        }
    } else if(count.count === VOTE_NUM) {
        $('.weui_btn_primary').removeClass('weui_btn_disabled');
    } else if(count.count > VOTE_NUM) {
        checkbox.checked = !checkbox.checked;    //手动触发checkbox的点击事件
        confirm('不能超过5票');
        count.reduce();
    }
});
/**
 * 弹出层,黑黑的那种
 * @param  {string} msg  提示信息,建议短一点,不然不好看
 * @param  {number} time 弹出后自动隐藏的时间,可选,默认1秒
 */
function remind(msg, time) {
    var t = time || 1000;
    $('#loadingToast').hide();
    $('.weui_toast_content').text(msg);
    $('#toast').show();
    setTimeout(function() {
        $('#toast').hide();
    }, t);
}

/**
 * 弹出层,弹出确定
 * @param  {string} msg 弹出提示的描述
 * @param  {string} title 弹出提示的标题
 */
function confirm(msg, title) {
    var title = title || '提示';
    $('#loadingToast').hide();
    $('.weui_dialog_bd').text(msg);
    $('.weui_dialog_title').text(title);
    $('.weui_dialog_alert').show();
}

// 提交按钮点击事件
$('#submit_btn').on('click', function() {
    if(count.count !== VOTE_NUM) return false;      //不够5票不给点
    confirm('投票活动已经结束啦');
    // var selected = [];

    // $('.weui_check:checked').each(function(index, item) {
    //     selected.push(item.name);
    // });

    // console.log(selected.join(','));
    // $('#loadingToast').show();
    // $.ajax({
    //     type: 'POST',
    //     url: '/vote2016/vote',
    //     timeout: 10000,
    //     data: {
    //         Aid: selected.join(',')
    //     },
    //     success: xhrSuccess,
    //     error: xhrFail
    // });
});

//ajax成功
function xhrSuccess(data, status, xhr) {
    data = JSON.parse(data);
    if(data.status === 200 && data.info === 'success') {
        remind('提交成功');
        location.reload();      
    } else if(data.status === 200 && data.info === 'fail') {
        confirm('你今天已经投过票了');
    } else if(data.status === 400 && data.info === 'fail') {
        confirm('你没关注重邮小帮手或没绑定学号');
    }
}

// ajax失败处理
function xhrFail(xhr, errorType, error) {
    if(errorType === 'error') {
        confirm('请求错误你没关注重邮小帮手或没绑定学号');
    } else if(errorType === 'timeout') {
        remind('请求超时');
    }
}
